package com.xyhy.starter.mfx.utils;

import com.mybatisflex.core.paginate.Page;
import com.xyhy.core.utils.BeanUtils;
import com.xyhy.core.utils.jdk.StreamUtil;
import com.xyhy.core.web.model.page.PageResult;
import com.xyhy.core.web.model.page.PurePageQO;
import lombok.NonNull;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

public class PageUtil {

  public static <T> Page<T> of(PurePageQO qo) {
    return new Page<T>(qo.getPage(), qo.getSize());
  }

  public static <T> PageResult<T> responseOf(Page<T> page) {
    return new PageResult<T>().setPage((int) page.getPageNumber()).setSize((int) page.getPageSize())
            .setTotalPage((int) page.getTotalPage()).setTotal(page.getTotalRow())
            .setRecords(page.getRecords());
  }

  public static <T, U> PageResult<U> convert(PageResult<T> pageResult, @NonNull Function<T, U> converter) {
    return new PageResult<U>().setPage(pageResult.getPage()).setSize(pageResult.getSize())
            .setTotalPage(pageResult.getTotalPage()).setTotal(pageResult.getTotal())
            .setRecords(StreamUtil.toList(pageResult.getRecords(), converter));
  }

  public static <T, U> PageResult<U> responseOf(PageResult<T> pageResult, @NonNull Function<T, U> converter) {
    return convert(pageResult, converter);
  }

  public static <T, U> PageResult<U> responseOf(PageResult<T> pageResult, @NonNull List<U> data) {
    return new PageResult<U>().setPage(pageResult.getPage()).setSize(pageResult.getSize())
            .setTotalPage(pageResult.getTotalPage()).setTotal(pageResult.getTotal())
            .setRecords(data);
  }

  public static <T, U> PageResult<U> responseOf(PageResult<T> pageResult, Class<U> uClass, Consumer<List<U>> consumer) {
    List<U> data = BeanUtils.toBeans(pageResult.getRecords(), uClass);
    consumer.accept(data);
    return new PageResult<U>().setPage(pageResult.getPage()).setSize(pageResult.getSize())
            .setTotalPage(pageResult.getTotalPage()).setTotal(pageResult.getTotal())
            .setRecords(data);
  }

}
